package com.ldzg.blockwatcher.watcher.tron;

import cn.hutool.json.JSONUtil;
import com.ldzg.blockwatcher.config.tron.TronProperties;
import com.ldzg.blockwatcher.notify.enums.NotifySourceEnum;
import com.ldzg.blockwatcher.notify.factory.NotifyFactory;
import com.ldzg.blockwatcher.risk.RiskEngine;
import com.ldzg.blockwatcher.utils.ThreadPoolUtil;
import com.ldzg.blockwatcher.watcher.AbstractWatcher;
import com.ldzg.blockwatcher.watcher.tron.dto.TronTransactionDTO;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.atomic.AtomicBoolean;

/**
 *  波厂连 黑名单监听
 *
 * @author 18310740596@163.com
 * @version V1.0.0
 * @since 2025-07-02 15:55:36
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class TronBlackListWatcher extends AbstractWatcher {

    private static final int MAX_CAPACITY = 2048;

    public static final BlockingQueue<TronTransactionDTO> DATA_QUEUE = new LinkedBlockingQueue<>(MAX_CAPACITY);

    private final AtomicBoolean running = new AtomicBoolean(Boolean.TRUE);

    private final NotifyFactory notifyFactory;

    /**
     *  数据进入队列
     *
     * @param transaction 黑名单信息
     */
    public static void enqueue(TronTransactionDTO transaction) {
        boolean ignore = DATA_QUEUE.offer(transaction);
    }

    @Override
    public void watcher() {
        log.info("波厂连 加入黑名单监听");
        while (running.get()) {
            try {
                TronTransactionDTO transaction = DATA_QUEUE.take();
                // 处理交易
                ThreadPoolUtil.execute(() -> watcherPostHandler(transaction));
            } catch (InterruptedException ignore) {}
        }
    }


    private void watcherPostHandler(TronTransactionDTO transaction) {
        log.info("消费数据:{}", JSONUtil.toJsonStr(transaction));
        // 此处扩展 处理冻结信息
        notifyFactory.getStrategy().freezeAddress(NotifySourceEnum.TRON, transaction.getResult().getFrom());
    }

    @Override
    public void dispose() {
        running.set(Boolean.FALSE);
    }
}
